"""
用户管理控制器
提供用户的搜索、更新、删除等功能
支持用户组管理和权限控制
"""
from typing import List, Optional

from loguru import logger
from pydantic import BaseModel
from fastapi import Request

from schemas.response_entity import JsonModel
from db.repository.user import (
    db_get_group_by_id,
    db_search_users,
    db_get_user_by_id,
    db_soft_delete_user,
    db_remove_user_from_all_groups,
    db_update_user,
    db_check_user_in_group,
    db_bulk_add_users_to_group,
    db_get_user_groups,
    db_get_user_group_ids
)


# ==================== 数据模型定义 ====================
class UserDelEntity(BaseModel):
    """用户删除实体"""
    token: str
    user_id: int


class GroupUserEntity(BaseModel):
    """用户组用户操作实体"""
    user_ids: List[int]
    group_id: int
    token: str


class UserUPEntity(BaseModel):
    """用户更新实体"""
    token: str
    old_password: str = None
    new_password: str = None
    nickname: str = None
    company: str = None


class UserCompanyUpdate(BaseModel):
    token: str  # 从请求中获取 token
    company_name: Optional[str] = None
    tax_id: Optional[str] = None
    email: Optional[str] = None


# ==================== API接口函数 ====================

# 获取用户信息
async def get_user_info(request: Request, token: str):
    """
    获取用户信息
    
    Args:
        request: FastAPI请求对象
        token: 用户认证token
        
    Returns:
        JsonModel: 用户信息响应
    """
    user = request.state.user
    if user is None:
        return JsonModel(code=401, data=None, msg=f"用户token 非法").to_response()
    user_info = user.to_json()
    return JsonModel(code=200, data=user_info, msg="success").to_response()


# 搜索用户
async def search_users(request: Request, token: str, username: str = None):
    """
    搜索用户
    
    Args:
        request: FastAPI请求对象
        token: 用户认证token
        username: 可选的用户名过滤条件
        
    Returns:
        JsonModel: 用户列表响应
    """
    user = request.state.user
    if user is None:
        return JsonModel(code=401, data=None, msg=f"用户token 非法").to_response()
    
    try:
        if user.check_superman_role():
            # 超级管理员可以搜索所有用户
            users = db_search_users(username=username)
        else:
            # 普通用户只能搜索同组用户
            user_groups = db_get_user_group_ids(user)
            users = db_search_users(username=username, user_groups=user_groups)

        if len(users) == 0:
            return JsonModel(code=404, data=None, msg=f"用户未匹配到").to_response()

        data = []
        for user_obj in users:
            groups = db_get_user_groups(user_obj.id)
            user_info = user_obj.to_json()
            user_info["groups"] = [{"name": g.name, "description": g.description, "id": g.id} for g in groups]
            data.append(user_info)
        
        return JsonModel(code=200, data=data, msg="success").to_response()
    except Exception as e:
        logger.error(f"搜索用户失败: {str(e)}")
        return JsonModel(code=500, data=None, msg="服务器内部错误").to_response()


# 删除用户
async def delete_user(request: Request, payload: UserDelEntity):
    """
    删除用户
    
    Args:
        request: FastAPI请求对象
        payload: 用户删除数据
        
    Returns:
        JsonModel: 删除结果响应
    """
    user = request.state.user
    if user is None:
        return JsonModel(code=401, data=None, msg=f"用户token 非法").to_response()
    
    try:
        if not user.check_admin_role():
            return JsonModel(code=403, data=None, msg=f"用户无权限").to_response()
        
        if user.id == payload.user_id:
            return JsonModel(code=400, data=None, msg=f"用户不能删除自己").to_response()
        
        del_user = db_get_user_by_id(payload.user_id)
        if del_user is None:
            return JsonModel(code=404, data=None, msg=f"用户未找到").to_response()
        
        # 软删除用户
        db_soft_delete_user(payload.user_id)
        
        # 从所有组中移除用户
        db_remove_user_from_all_groups(payload.user_id)
        
        return JsonModel(code=200, data=None, msg=f"用户{del_user.nickname} 已被删除").to_response()
    except Exception as e:
        logger.error(f"删除用户失败: {str(e)}")
        return JsonModel(code=500, data=None, msg="服务器内部错误").to_response()


# 用户加入组
async def user_join_group(request: Request, payload: GroupUserEntity):
    """
    用户加入组
    
    Args:
        request: FastAPI请求对象
        payload: 用户组用户操作数据
        
    Returns:
        JsonModel: 操作结果响应
    """
    user = request.state.user
    if user is None:
        return JsonModel(code=401, data=None, msg="用户token 非法").to_response()
    
    try:
        # 验证用户组是否存在
        group = db_get_group_by_id(payload.group_id, user)
        if not group:
            return JsonModel(code=404, data=None, msg="用户组未匹配到").to_response()

        # 验证当前用户是否有权限操作该用户组
        if group.owner != user.id and not user.is_admin:
            return JsonModel(code=403, data=None, msg="用户未获取当前用户组的管理权限").to_response()

        # 批量查询用户是否存在
        users = db_search_users(user_ids=payload.user_ids)
        if len(users) != len(payload.user_ids):
            missing_users = set(payload.user_ids) - {u.id for u in users}
            return JsonModel(code=404, data=None, msg=f"以下用户未匹配到: {missing_users}").to_response()

        # 检查用户是否已经在目标用户组中
        for user_id in payload.user_ids:
            if db_check_user_in_group(user_id, payload.group_id):
                return JsonModel(code=400, data=None, msg=f"用户{user_id}已在用户组中").to_response()

        # 批量将用户添加到组
        db_bulk_add_users_to_group(payload.user_ids, payload.group_id)

        return JsonModel(code=200, data=None, msg="success").to_response()
    except Exception as e:
        logger.error(f"用户加入组失败: {str(e)}")
        return JsonModel(code=500, data=None, msg="服务器内部错误").to_response()


# 更新用户
async def update_user(request: Request, payload: UserUPEntity):
    """
    更新用户信息
    
    Args:
        request: FastAPI请求对象
        payload: 用户更新数据
        
    Returns:
        JsonModel: 更新结果响应
    """
    user = request.state.user
    if user is None:
        return JsonModel(code=401, data=None, msg=f"用户token 非法").to_response()
    
    try:
        if not payload.old_password and payload.new_password:
            return JsonModel(code=400, data=None, msg="请输入旧密码").to_response()
        
        if payload.old_password and not user.verify_password(payload.old_password):
            return JsonModel(code=400, data=None, msg="旧密码不正确").to_response()
        
        # 更新用户信息
        db_update_user(
            user.id,
            nickname=payload.nickname,
            company=payload.company,
            password=payload.new_password
        )

        return JsonModel(code=200, data=None, msg=f"用户更新成功").to_response()
    except Exception as e:
        logger.error(f"更新用户失败: {str(e)}")
        return JsonModel(code=500, data=None, msg="服务器内部错误").to_response()


# async def read_user_company(request: Request, token: str):
#     current_user = get_current_user(token, credentials_exception=None, db=db)
#     # 验证 token 并获取当前用户
#     if current_user is None:
#         raise HTTPException(status_code=400, detail="用户 token 非法")

#     current_user = current_user["user"]

#     # 查询用户公司信息
#     db_user_company = db.query(UserCompany).filter(
#         UserCompany.user_id == current_user.id  # 确保用户只能查询自己的数据
#     ).first()

#     if db_user_company is None:
#         return JsonModel(code=404, data=None, msg="未找到对应的信息")

#     return JsonModel(code=200, data=db_user_company.to_json(), msg="查询成功").to_response()


# async def update_user_company(request: Request, payload: UserCompanyUpdate):
#     user = request.state.user
#     if user is None:
#         return JsonModel(code=401, data=None, msg=f"用户token 非法").to_response()

#     try:
#         current_user = get_current_user(user_company.token, credentials_exception=None, db=db)
#     # 验证 token 并获取当前用户
#     if current_user is None:
#         raise HTTPException(status_code=400, detail="用户 token 非法")

#     current_user = current_user["user"]

#     # 查询需要更新的公司信息
#     db_user_company = db.query(UserCompany).filter(
#         UserCompany.user_id == current_user.id  # 确保用户只能操作自己的数据
#     ).first()

#     # 如果记录不存在，则创建一条新记录
#     if db_user_company is None:
#         db_user_company = UserCompany(
#             user_id=current_user.id,  # 关联当前用户
#             company_name=user_company.company_name,
#             tax_id=user_company.tax_id,
#             email=user_company.email
#         )
#         db.add(db_user_company)
#         db.commit()
#         db.refresh(db_user_company)
#         return JsonModel(code=200, data=None, msg="创建成功")

#     # 如果记录存在，则更新字段
#     if user_company.company_name is not None:
#         db_user_company.company_name = user_company.company_name
#     if user_company.tax_id is not None:
#         db_user_company.tax_id = user_company.tax_id
#     if user_company.email is not None:
#         db_user_company.email = user_company.email

#     db.commit()
#     db.refresh(db_user_company)

#     return JsonModel(code=200, data=None, msg="更新成功")


